<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.schoolName" placeholder="学校名称"  style="width:180px;" clearable ></el-input>
				</el-form-item>
				<el-form-item>
					<el-select v-model="filters.isGraduated" placeholder="请选择毕业状态" style="width:150px;" clearable>
					<el-option v-for="(item, index) in isGraduatedOptions" :key="index" :label="item.label"
						:value="item.value" ></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-input v-model="filters.userName" placeholder="学生姓名"  style="width:180px;" clearable ></el-input>
				</el-form-item>
				<el-form-item>
					<el-input v-model="filters.account" placeholder="账号"   style="width:180px;" clearable ></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getStudents">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleMove" :disabled="this.sels.length===0">转校</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="tableData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="30">
			</el-table-column>
			<el-table-column type="index" label="序号" width="50" fixed>
				<template slot-scope="scope">   
                    {{pageSize*(nowPage-1)+scope.$index+1}}
                </template>
			</el-table-column>
			<el-table-column prop="userName" label="姓名" width="90" align='center'>
			</el-table-column>
			<el-table-column prop="account" label="用户账号" width="120" align='center'>
			</el-table-column>
			<el-table-column  label="所属地区" width="150" align='center' >
				<template slot-scope="scope">
                    {{scope.row.provinceName}}{{scope.row.cityName == '市辖区'?'':scope.row.cityName}}{{scope.row.districtName== '市辖区'?'':scope.row.districtName}}
                </template>
			</el-table-column>
			<el-table-column prop="schoolName" label="所属学校" min-width="130" align='center'>
			</el-table-column>
			<el-table-column prop="classesName" label="班级" min-width="120" align='center'>
			</el-table-column>
			<el-table-column prop="useType" label="状态" width="50">
				<template slot-scope="scope">
					{{scope.row.useType=="0"?"正常":"停用"}}
				</template>
			</el-table-column>
			<el-table-column label="操作" width="250" align='center' fixed="right">
				<template slot-scope="scope">
					<el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="info" v-if="scope.row.useType==0" size="small" @click="offStudent(scope.row)">停用</el-button>
					<el-button v-else type="success" size="small" @click="onStudent(scope.row)">启用</el-button>
					<el-button type="warning" size="small" @click="resetpassword(scope.row)">重置</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-pagination background layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="text-align: center; ">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="editType" :visible.sync="editFormVisible" :close-on-click-modal="false" v-loading="editLoading">
			<el-form :model="studentForm" label-width="120px" :rules="studentRules" ref="studentForm">
				<el-form-item label="学生姓名：" prop="userName">
					<el-input v-model="studentForm.userName" placeholder="请输入学生姓名，最长20个汉字" style="float:left;width:77%;" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别：" prop="gender">
					<el-select v-model="studentForm.gender" placeholder="请选择学生性别" :style="{width: '77%'}">
						<el-option v-for="(item, index) in genderOptions" :key="index" :label="item.label"
							:value="item.value+''" ></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="学藉号：" prop="studentNo">
					<el-input v-model="studentForm.studentNo" placeholder="请输入学生学藉号" style="float:left;width:77%;"></el-input>
				</el-form-item>
				<el-form-item label="所属地区：" prop="districtCode" required>
					<el-form-item prop="provinceCode" style="float:left;width:25%;">
						<el-select v-model="studentForm.provinceCode" @change="getCityListByProvince(studentForm.provinceCode)" placeholder="请选择省份">
							<el-option v-for="(item,index) in provinceList" :label="item.name" :value="item.code" :key="index"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="cityCode" style="float:left;width:25%;margin-left:5px;">
						<el-select v-model="studentForm.cityCode" :disabled="studentForm.provinceCode==''" @change="getDistrictListByCity(studentForm.cityCode)" placeholder="请选择地市">
							<el-option v-for="(item,index) in cityList" :label="item.name" :value="item.code" :key="index"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="districtCode" style="float:left;width:25%;margin-left:5px;">
						<el-select v-model="studentForm.districtCode" :disabled="studentForm.cityCode==''" @change="getSchoolListByCounty(studentForm.provinceCode,studentForm.cityCode,studentForm.districtCode)" placeholder="请选择区县">
							<el-option v-for="(item,index) in districtList" :label="item.name" :value="item.code" :key="index"></el-option>
						</el-select>
					</el-form-item>
				</el-form-item>
				<el-form-item label="所属学校：" prop="schoolId">
					<el-select v-model="studentForm.schoolId" :disabled="studentForm.districtCode==''" placeholder="请选择所属学校"  style="float:left;width:77%;">
						<el-option v-for="(item,index) in schoolList" :label="item.schoolName" :value="item.schoolId" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="手机号：" prop="phone">
					<el-input v-model="studentForm.phone" @keyup.native="validatePhone('studentForm')" placeholder="请输入手机号" style="float:left;width:77%;"></el-input>
				</el-form-item>
				
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		 <!-- 学生转校 -->
        <el-dialog title="转校" v-if="moveSchoolVisible" :visible.sync="moveSchoolVisible" >
            <el-form ref="moveSchool" :model="moveForm" label-width="110px">
                <el-form-item label="所属地区：" required>
					<el-form-item prop="provinceCode" style="float:left;width:25%;">
						<el-select v-model="moveForm.provinceCode" @change="getCityListByProvince(moveForm.provinceCode)" placeholder="请选择省">
							<el-option v-for="(item,index) in provinceList" :label="item.name" :value="item.code" :key="index"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="cityCode" style="float:left;width:25%;margin-left:5px;">
						<el-select v-model="moveForm.cityCode" :disabled="moveForm.provinceCode==''" @change="getDistrictListByCity(moveForm.cityCode)" placeholder="请选择市">
							<el-option v-for="(item,index) in cityList" :label="item.name" :value="item.code" :key="index"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="districtCode" style="float:left;width:25%;margin-left:5px;">
						<el-select v-model="moveForm.districtCode" :disabled="moveForm.cityCode==''" @change="getSchoolListByCounty(moveForm.provinceCode,moveForm.cityCode,moveForm.districtCode)" placeholder="请选择区/县">
							<el-option v-for="(item,index) in districtList" :label="item.name" :value="item.code" :key="index"></el-option>
						</el-select>
					</el-form-item>
				</el-form-item>
				<el-form-item label="所属学校：" prop="schoolId" required>
					<el-select v-model="moveForm.schoolId" :disabled="moveForm.districtCode==''" placeholder="请选择所属学校"  style="float:left;width:77%;">
						<el-option v-for="(item,index) in schoolList" :label="item.schoolName" :value="item.schoolId" :key="index"></el-option>
					</el-select>
				</el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="moveSchoolVisibleClose">取 消</el-button>
                <el-button type="primary" @click="moveSchool">确 定</el-button>
            </div>
        </el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	//import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';
	import { SysApi } from '@/api/index'

	export default {
		data() {
			var checkPhone = (rule, value, callback) => {
				if (!value) {
					callback();
				} else {
					const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
					
					if (reg.test(value)) {
						callback();
					} else {
						return callback(new Error('请输入正确的手机号'));
					}
				}
			};
			return {
				filters: {
					schoolId: '',
					userName: '',
					account: '',
					schoolName: '',
					isGraduated: '',
				},
				sels: [],//列表选中列
				tableData: [],
				provinceList: [],
				cityList: [],
				districtList: [],
				total: 0,
				listLoading: true,
				schoolName: '',
				schoolId:  '',
				provinceCode: '',
				cityCode: '',
				districtCode: '',

				//学生信息表单
				studentForm: {
					schoolId:  '',
					provinceCode: '',
					cityCode: '',
					districtCode: '',
					userId: '',
					userName: '',
					phone: '',
					gender: '',
					studentNo: '',
					phaseId: 1,
					roleId: '',
					type: '',
					useType: ''
				},

				moveForm: {
					schoolId: '',
					provinceCode: '',
					cityCode: '',
					districtCode: '',
				},

				genderOptions: [{
					"label": "男",
					"value": 0
				}, {
					"label": "女",
					"value": 1
				}],

				isGraduatedOptions: [{
					"label": "在读",
					"value": 0
				}, {
					"label": "已毕业",
					"value": 1
				}, {
					"label": "全部",
					"value": 2
				}],

				editType: '',

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,

				moveSchoolVisible: false,//转校界面是否显示

				studentRules: { //学生信息表单验证
					userName:[
						{ required: true, message: '请输入学生姓名', trigger: 'blur' },
						{ min: 1, max: 20, message: '姓名长度为 1 到 20 个字符', trigger: ['blur','change'] }
					],
					gender:[
						{ required: true, message: '请选择性别', trigger: 'blur' }
					],
					roleId:[
						{ required: true, type: 'number', message: '请选择角色', trigger:  ['blur','change'] }
					],
					studentNo:[
						{ required: true, message: '请输入学生学籍号', trigger: 'blur' }
					],
					schoolId:[
						{ required: true, type: 'number',message: '请选择所属学校', trigger:  ['blur','change'] }
					]
            },
            roleList:[],
            pageSize:10,
            nowPage:1,
            phaseList:[],
            schoolList:[],
            roleLevel:0,

			}
		},
		created(){
		
			//获取学生列表
			this.getStudents();
			//获取学段列表
			this.getPhaseList();
			//获取省列表
			this.getProvinceList()
		},
		mounted() {
			 //获取学生列表
			this.getStudents();
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.nowPage = val;
				this.getStudents();
			},
			//获取学段列表
			getPhaseList(){
				let params = {
					schoolId: this.schoolId
				};
				SysApi.getSchoolPhaseList(params, res => {
					if (res!=null)
					{
						this.phaseList = res;
						
					}
				}, (errorType, error) => {
				})
			},
			//获取省列表
			getProvinceList(){
				let params = {
					parentcode: '0'

				};
				this.loading_search = true;
				SysApi.getDistrictList(params,res =>{
					this.provinceList = res;
					this.loading_search = false;
				}, (errorType, error) => {
					this.loading_search = false;
				})
			},
			//市相对省联动
			getCityListByProvince(parentcode){
				
				let params = {
					parentcode: parentcode
				};
				this.loading_search = true;
				SysApi.getDistrictList(params,res =>{
					this.cityList = res;
					this.filters.cityCode =  '';
						this.filters.districtCode =  '';
						this.loading_search = false;
				}, (errorType, error) => {
					this.loading_search = false;
				})
			
			},
			//区相对市联动
			getDistrictListByCity(parentcode){
				
				let params = {
					parentcode: parentcode
				};
				this.loading_search = true;
				SysApi.getDistrictList(params,res =>{
					this.districtList = res;
					this.filters.districtCode =  '';
					this.loading_search = false;
				}, (errorType, error) => {
					this.loading_search = false;
				})
				
			},
			//学校相对所在地区联动
			getSchoolListByCounty(provinceCode,cityCode,districtCode){
				this.moveForm.schoolId =  '';
				//this.studentForm.schoolId =  '';
				this.$set(this.studentForm,'schoolId','');
				let params = {
					provinceCode: provinceCode,
					cityCode: cityCode,
					districtCode: districtCode
				}
				
				SysApi.getSchoolList(params,res =>{
					this.schoolList = res;
					
				}, (errorType, error) => {})
			},
			//获取用户列表
			getStudents() {
				let params = {
					pageNum: this.nowPage,
					pageSize: this.pageSize,
					userName: this.filters.userName,
					account: this.filters.account,
					schoolName: this.filters.schoolName,
					isGraduated: this.filters.isGraduated
				};
				this.listLoading = true;

				SysApi.getStudentListPage(params,res =>{
					
					this.total = res.total;
					this.tableData = res.list;
					this.listLoading = false;
				}, (errorType, error) => {

					this.listLoading = false;
				})


			},
			//学生手机号，只能输入正整数限制
			validatePhone(str){
				if(str== "studentForm"){
					this.studentForm.phone = this.studentForm.phone.replace(/[^\.\d]/g,'');
					this.studentForm.phone = this.studentForm.phone.replace('.','');
				}else{
					// this.filters.phone = this.filters.phone.replace(/[^\.\d]/g,'');
					// this.filters.phone = this.filters.phone.replace('.','');
				}
			},
			//改变角色
			changeRole(roleId){
				for(let i = 0; i < this.roleList.length; i++){
					if(this.roleList[i].roleId == roleId){
						this.roleLevel = this.roleList[i].roleLevel
					}
				}
			},
			//删除
			handleDel: function (row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					
					this.listLoading = true;
		
					let params = {
						 userId: row.userId,
						 schoolId: row.schoolId
						 };

					SysApi.deleteStudent(params,res =>{
						this.listLoading = false;
						if (res!=null)
						{
							this.$message({
								message: '删除成功',
								type: 'success'
							});
						}
						this.getStudents();
					}, (errorType, error) => {
						this.listLoading = false;
					}).catch((error) => {
						this.listLoading = false;
					})
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (row) {
				this.editType = "编辑";
				this.editLoading = true;
				this.studentForm = {
					userId: row.userId,
					userName: row.userName,
					phone: row.phone,
					roleId: row.roleId,
					gender: row.gender,
					studentNo: row.studentNo,
					phaseId: row.phaseId
				},

				this.changeRole(row.roleId)
				this.userId = row.userId;
				this.studentForm.provinceCode=row.provinceCode
				this.getCityListByProvince(row.provinceCode);
				this.studentForm.cityCode=row.cityCode
				this.getDistrictListByCity(row.cityCode);
				this.studentForm.districtCode=row.districtCode

				this.getSchoolListByCounty(row.provinceCode,row.cityCode,row.districtCode)
				//this.studentForm.schoolId = row.schoolId
				this.$set(this.studentForm,'schoolId',row.schoolId);
	
				
				this.editFormVisible = true;
				this.editLoading = false;
				//this.studentForm = Object.assign({}, row);
				
			},
			
			//编辑
			editSubmit: function () {
				this.$refs.studentForm.validate((valid) => {
					if (valid) {
							//NProgress.start();
							let params = Object.assign({}, this.studentForm);
							
							SysApi.saveStudent(params,res =>{
								this.listLoading = false;
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['studentForm'].resetFields();
								this.editFormVisible = false;
								this.getStudents();
							}, (errorType, error) => {
	
							})
							
					}
				});
			},
			resetpassword(row){
				this.$confirm('是否重置密码', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					SysApi.resetStudent({
						userId: row.userId
					}, res => {
						this.$message({type: 'success', message: '重置密码成功!'})
						this.getStudents();
					}, (errorType, error) => {
						this.$message({type: 'error', message: '重置密码失败!'})
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//显示编辑界面
			handleMove: function () {
			
				this.moveSchoolVisible = true;
				this.moveForm.provinceCode = ''
				this.moveForm.cityCode = ''
				this.moveForm.districtCode = ''
				
			},
			moveSchoolVisibleClose: function () {
			
				this.moveSchoolVisible = false;
				
			},
			//批量转校
			moveSchool: function () {
				var ids = this.sels.map(item => item.userId).toString();
				this.$confirm('确认将选中学生转校吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;

					let params = {
						 studentIds: ids,
						 schoolId: this.moveForm.schoolId,
						 classesId: 0
						 };

					SysApi.moveStudent(params).then((res) => {

						this.$message({
							message: '转校成功',
							type: 'success'
						});
						this.getStudents();
						this.listLoading = false;
						this.moveSchoolVisible = false;
					});
				}).catch(() => {

				});
			},
			onStudent(row){
				this.$confirm('是否启用该学生?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.listLoading = true;

					let params = {
						 userId: row.userId
						 };
					
					SysApi.onStudent(params).then((res) => {

						this.$message({
							message: '启用成功',
							type: 'success'
						});
						this.getStudents();
						this.listLoading = false;
						}, (errorType, error) => {
						this.$message({type: 'error', message: '启用失败!'})
					})

				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
			},
			offStudent(row) {
				this.$confirm('是否停用该学生?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.listLoading = true;

					let params = {
						 userId: row.userId
						 };
					
					SysApi.offStudent(params).then((res) => {

						this.$message({
							message: '停用成功',
							type: 'success'
						});
						this.getStudents();
						this.listLoading = false;

					}, (errorType, error) => {
						this.$message({type: 'error', message: '停用失败!'})
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
			}
			
		},
		
	}

</script>

<style>
.el-table >.el-table__fixed {
    height: 100% !important; 
  }
.el-table >.el-table__fixed-right {
    height: 100% !important; 
  }
.el-table--scrollable-x .el-table__body-wrapper {
    z-index: 1;
  }
</style>